<!-- 资讯管理 -->
<template>
    <div class="app-container">
        <div class="container">
            <el-row>
                <el-form :inline="true" :model="listQuery">
                    <!-- <el-form-item label="ID">
                        <el-input v-model="listQuery.id" placeholder="ID" clearable />
                    </el-form-item> -->
                    <el-form-item label="用戶名">
                        <el-input v-model="listQuery.email" placeholder="用戶名" clearable />
                    </el-form-item>
                    <el-form-item label="昵称">
                        <el-input v-model="listQuery.nickname" placeholder="昵称" clearable />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="listQuery.note" placeholder="备注" clearable />
                    </el-form-item>
                    <el-form-item label="状态" >
                        <el-select v-model="listQuery.status" placeholder="状态" clearable >
                            <el-option v-for="item in Object.keys(statusDesc)" :label="statusDesc[item]" :key="item"
                                :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSearch">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-table :data="list" v-loading="listLoading" element-loading-text="拼命加载中" border fit
                    highlight-current-row>
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
                    <el-table-column label="昵称" align="center">
                        <template #default="scope">
                            {{  scope.row.nickname}}
                            <div style="font-size: 12px;" v-if="scope.row.note">备注：{{ scope.row.note }}</div>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="vip" label="用户类型" width="95"  align="center">
                        <template #default="scope">
                            <el-tag>{{ scope.row.vip > 0 && scope.row.status == 0 ? 'VIP' : '普通用户' }}</el-tag>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="状态" width="95" align="center">
                        <template #default="scope">
                            <el-tag>{{ statusDesc[scope.row.status] }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="会员信息"  align="center">
                        <template #default="scope">
                            <div class="vip" v-if="scope.row.leftDays">
                                <!-- 订阅类型 -->
                                <el-tag >{{ getSubscribeDesc(scope.row) }}</el-tag>
                                <div>
                                    <!-- 单独订阅策略 -->
                                    <el-tag v-if="!scope.row.subscribeType && scope.row.subStrategyIds && scope.row.subStrategyIds.length">{{ getStategyNames(scope.row.subStrategyIds) }}</el-tag>
                                    <!-- 剩余天数 -->
                                    <div v-if="scope.row.leftDays">剩余{{ scope.row.leftDays }}天</div>
                                    <!-- 到期时间 -->
                                    <div v-if="scope.row.memberEndTime">会员到期:{{ scope.row.memberEndTime }}</div>
                                </div>
                            </div>

                            <span v-else>未订阅</span>
                        </template>
                    </el-table-column>
                    
                    <!-- <el-table-column label="更新日期"  align="center">
                        <template #default="scope">
                            <span>{{ scope.row.subscribeTime || scope.row.updateTime }}</span>
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="createTime" label="订阅日期" width="160" align="center"></el-table-column>
                    <el-table-column prop="memberEndTime" label="会员到期时间" width="160" align="center"></el-table-column>
                    <el-table-column prop="leftDays" label="剩余天数" width="160" align="center"></el-table-column>
                    <!-- <el-table-column prop="createTime" label="创建日期" width="160" align="center"></el-table-column> -->
                    <!-- <el-table-column prop="note" label="备注" width="160" align="center"></el-table-column> -->
                    <el-table-column label="操作" align="center" width="225">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button link type="primary" 
                                @click="$router.push({
                                    name: 'UserInvite',
                                    query: {
                                        id: scope.row.id,
                                    }
                                })">邀请</el-button>
                            <el-button link type="primary" 
                                @click="handleChangePoints(scope.row)">充值</el-button>
                            <el-button link type="primary" v-if="scope.row.status === 99"
                                @click="handleStatus(scope.row, '0')">启用</el-button>
                            <el-button link type="primary"  v-if="scope.row.status === 0"
                                @click="handleStatus(scope.row, '99')">禁用</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination layout="sizes, total, prev, pager, next" :page-sizes="[10, 20, 30]"
                        v-model:page-size="listQuery.rows" v-model:currentPage="listQuery.page"
                        @current-change="(val) => { fetchData() }" @size-change="(val) => { fetchData() }"
                        :total="totalRecord"></el-pagination>
                </div>
            </el-row>
            <el-dialog title="资金账户变动" v-model="dialogVisiable" :close-on-click-modal="false" width="600px">
                <el-form ref="form" :model="form" label-width="120px">
                    <el-form-item label="充值时间" :label-width="formLabelWidth" prop="chargeType"
                        :rules="[{ required: true, message: '请输入充值时间', trigger: 'blur' }]">
                        <el-select v-model="form.chargeType" placeholder="请输入充值时间" style="width: 300px;">
                            <el-option v-for="item in chargeTypeList" :key="item" :label="item" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="充值金额" :label-width="formLabelWidth" prop="charging_money"
                        :rules="[{ required: true, message: '请输入充值金额', trigger: 'blur' }]">
                        <el-input-number v-model="form.charging_money" style="width: 300px;" :min="1"
                            placeholder="请输入充值金额"></el-input-number>
                    </el-form-item>
                    <el-form-item label="会员类型" :label-width="formLabelWidth" prop="subscribeType">
                        <el-select v-model="form.subscribeType" placeholder="请选择会员类型" style="width: 300px;" @change="handleChangeSubscribeType">
                            <el-option label="一卡通" :value="1"></el-option>
                            <el-option label="单独订阅" :value="0"></el-option>
                        </el-select>
                        <div class="strategy-list" v-if="form.subscribeType === 0">
                            <el-checkbox
                                v-model="checkAll"
                                :indeterminate="isIndeterminate"
                                @change="handleCheckAllChange"
                                >全选</el-checkbox
                            >
                            <el-checkbox-group
                                v-model="checkedStrategy"
                                @change="handleCheckedStrategyChange"
                            >
                                <el-checkbox v-for="item in strategyList" :key="item.id" :label="item.id">{{
                                item.strategyName
                                }}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                    
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="handleClearVip">清空会员</el-button>
                        <el-button @click="dialogVisiable = false">取 消</el-button>
                        <el-button type="primary" @click="onSubmitPointsChange()" :loading="formLoading">提交</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { querySubscribeList, getStatus, changeStatus, getTeamMember } from '@/api/user'
import { utilsMixin } from '@/mixin/utils'
import { strategyList } from './strategy-mock';
import { chargeCreate, getChargeType, clearVip } from '@/api/charge';


export default {
    name: 'UserList',
    mixins: [utilsMixin],
    data() {
        return {
            chargeTypeList: [],
            checkedStrategy: [],
            isIndeterminate: false,
            checkAll: false,
            list: null, // 列表数据
            listLoading: true, // 加载状态
            totalRecord: 0, // 数据总条数
            listQuery: { page: 1, rows: 10 },
            listQueryParam: { page: 1 },
            statusDesc: getStatus(),
            dialogVisiable: false,
            changeUserId: 0,
            formLoading: false,
            formLabelWidth: '130',
            loading: false,
            teamInfo: [],
            dialogTeamVisible: false,
            dialogBalanceVisible: false,
            dialogTeamMemberVisible: false,
            balanceUserId: '',
            currentUser: {},
            form: {
                type: 'add',
                accounttype: 'money',
                amount: 0,
                remarks: '',
                testDriver: 0, // 0:代表正式月会员，1:代表体验会员
                subscribeType: 1,
            },
            props: {
                label: 'name',
                children: 'zones',
            },
            currentPid: undefined
        }
    },
    computed: { 
        strategyList() {
            return this.$store.state.user.strategyList;
        }
    },
    created() {
        this.init();
        this.fetchData()
        
    },
    methods: {
        fetchData() {
            this.listLoading = true
            querySubscribeList(this.listQuery).then(response => {
                if (response.success && response.data != null) {
                    this.list = response.data.records
                    this.totalRecord = response.data.total
                }
                this.listLoading = false
            }).catch(() => {
                this.listLoading = false
            })
        },
        init() {
            // 获取会员时间列表
            this.getChargeType();
            console.log('strategyListinit', this.$store.state.strategyList)
            // this.strategyList = this.$store.state.strategyList || strategyList;
            
        },
        handleClearVip() {
            // 清空会员
            clearVip({ userId: this.currentUser.id}).then(res => {
                if (res.code === 20000) {
                    this.$message({
                        message: '清空成功！',
                        type: 'success'
                    });
                    this.fetchData();
                }
            })
        },
        getStategyNames(ids) {
            const nameArr = [];
            this.strategyList.forEach(item => {
                if (ids.includes(item.id)) {
                    nameArr.push(item.strategyName);
                }
            });
            return nameArr.join(',')
        },
        getSubscribeDesc(item) {
            if (!item.leftDays) return '';
            if (item.subscribeType == 1) {
                return '一卡通';
            } else {
                return '单独订阅';
            }
        },
        getChargeType() {
            getChargeType().then(res => {
                if (res.code === 20000) {
                    this.chargeTypeList = res.data;
                }
            });
        },
        handleChangeSubscribeType(value) {
            console.log('handleChangeSubscribeType====', value);
            console.log('handleChangeSubscribeType====', this.checkedStrategy);
            if (value === 1) {
                this.isIndeterminate = false;
                this.checkAll = true;
                this.checkedStrategy = [].concat(this.strategyList.map(item => item.id));
            } else {
                this.checkAll = false;
                this.isIndeterminate = false;
                this.checkedStrategy = [];
            }

        },
        handleCheckedStrategyChange(value) {
            console.log('========', value)
            const checkedCount = value.length
            this.checkAll = checkedCount === this.strategyList.length
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.strategyList.length
        },
        handleCheckAllChange (val) {
            this.checkedStrategy = val ? this.strategyList.map(item => item.id) : [];
            this.isIndeterminate = false
        },
        // 查询
        onSearch() {
            this.listQuery = Object.assign(this.listQuery, this.listQueryParam) // 合并对象
            this.fetchData()
        },
        handleStatus(row, status) {
            this.$confirm('是否进行此操作？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                changeStatus(row.id, status).then(() => {
                    this.fetchData()
                })
            }).catch(() => { })
        },
        handleEdit(row) {
            this.$router.push({ path: '/user/user-edit/' + row.id })
        },
        onCreate() {
            this.clearForm()
            this.addFormVisible = true
            this.isAdd = true
        },
        handleChangePoints(row) {
            this.dialogVisiable = true
            this.currentUser = row;
            this.form = {
                username: row.username,
                charging_money: 1,
                chargeType: '一个月',
                subscribeType: 1,
            }
        },
        onSubmitPointsChange() {
            // 充值新的
            
            const request = {
                userId: this.currentUser.id, //用户id
                chargeMoney: this.form.charging_money, //充值金额
                chargeType: this.form.chargeType, //充值时间  一个月/三个月
                subscribeType: this.form.subscribeType, //订阅方式 0 普通 1 畅享
                pushStrategyId: !this.form.subscribeType ? this.checkedStrategy.join(',') : '', //策略id
                quantity: this.form.charging_money, //充值金额
            };
            // 单独订阅
            if (!request.subscribeType) {
                if (!this.checkedStrategy.length) {
                    return this.$message({
                        message: '单独订阅至少选择一个策略',
                        type: 'error'
                    });
                }
                
                if (this.checkedStrategy.length >= 2) {
                    request.subscribeType = 1;
                    request.pushStrategyId = '';
                } 
            }
            this.formLoading = true
            chargeCreate(request).then(() => {
                this.formLoading = false
                this.dialogVisiable = false
                this.fetchData()
            }).catch(() => {
                this.formLoading = false
            })
        },
        viewTeamMember(id) {
            this.currentPid = id
            this.dialogTeamMemberVisible = true
        },
        loadNode(node, resolve) {
            let pid = this.currentPid
            if (node.data && node.data.id) {
                pid = node.data.id
            }
            getTeamMember(pid).then(resp => {
                if (resp.data) {
                    let data = resp.data.map(v => {
                        return { name: `ID ${v.id}=>${v.nickname} (${v.username}) 个人业绩 ${v.totalAchievement} 团队业绩 ${v.teamAchievement} 等级 ${v.memberLevel}`, id: v.id }
                    })
                    resolve(data)
                }
            })
        }
    }
}
</script>
<style  scoped>
.strategy-list {
    margin-top: 10px;
    
}
.strategy-list .el-checkbox-group {
    display: flex;
    flex-direction: column;
}
</style>